package com.maoshi.shop.coupon.comment.listener;

import com.google.common.collect.Lists;
import com.maoshi.shop.bean.event.BatchBindCouponEvent;
import com.maoshi.shop.bean.event.PaySuccessOrderEvent;
import com.maoshi.shop.bean.order.PaySuccessOrderOrder;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.coupon.comment.service.CouponService;
import com.maoshi.shop.coupon.comment.service.CouponUseRecordService;
import com.maoshi.shop.coupon.comment.service.CouponUserService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component("couponPaySuccessListener")
@AllArgsConstructor
public class PaySuccessOrderListener {

    private final CouponUseRecordService couponUseRecordService;
    private final CouponService couponService;
    private final CouponUserService couponUserService;

    /**
     * 更新优惠券使用记录状态
     */
    @EventListener(PaySuccessOrderEvent.class)
    @Order(PaySuccessOrderOrder.COUPON)
    public void couponPaySuccessListener(PaySuccessOrderEvent event) {
        if(Objects.equals(event.getOrders().get(0).getShopId(),Constant.PLATFORM_SHOP_ID)){
            return;
        }
        List<String> orderNumberList = Lists.newArrayList();
        List<com.maoshi.shop.bean.model.Order> orders = event.getOrders();

        for (com.maoshi.shop.bean.model.Order order : orders) {
            orderNumberList.add(order.getOrderNumber());
        }
        if (CollectionUtils.isNotEmpty(orderNumberList)) {
            couponUseRecordService.batchUpdateRecordByStatusAndOrderNums(2, orderNumberList);
        }

    }
    /**
     * 批量绑定优惠券
     */
    @EventListener(BatchBindCouponEvent.class)
    public void batchBindCouponEventListener(BatchBindCouponEvent event) {
        couponService.batchBindCouponByIds(event.getCouponIds(),event.getUserId(),event.getShopId());
    }
}
